<?php

class _site_handler {
	// Instantiated version of this object here
	public $this;

	// View accessible variables/methods
	public $BodyId;
	public $BodyClass;
	public $Section;
	public $PageHeading;
	public $ArchiveDisplay = 'genre';
	public $ArchiveType;
	public $ArchiveDname;
	public $ControllerFile;
	public $SelfLink = '';
	public $Url;
	public $MediaUrl;
	public $UpcomingEvents;
	public $UpcomingEventsAddLink;
	public $Title;
	public $CssFiles = array();
	public $JsFiles = array();

	public $GcmsEditModeOffLink;
	public $CmsAccess;
	public $GcmsEditModeLink;
	public $Wordlets;
	public $RootTitle;
	public $GcmsLogoutLink;
	public $GcmsLink;

	public $Options = array();
	public $DefaultPrefs = array();

	public $Pagination;

	public $SetCodeHtmlUrl;
	public $SetCodeBbUrl;

	public $EditMode;
	public $User;
	public $LoginUrl;
	public $RegisterUrl;

	public $M; // Monkake
	public $Code = 'ubb';
	public $Ajax = false;

	/* Initialize site */
	public function InitializeSite($m) {
		$this->M = $m;

		$m->IncludeModel('Site');
		$m->IncludeClass('Dbi');
		$m->IncludeModel('BaseOrm');
		$m->IncludeModel('Smiley');
		$m->IncludeModel('Tag');
		$m->IncludeModel('User');
		$m->IncludeModel('Post');
		$m->IncludeModel('Blog');
		$m->IncludeModel('SmileyTag');

		Dbi::$Address = $this->M->Get('DB_ADDR');
		Dbi::$Username = $this->M->Get('DB_USER');
		Dbi::$Password = $this->M->Get('DB_PASS');
		Dbi::$Database = $this->M->Get('DB_NAME');

		session_start();

		$this->Options['code'] = array('html' => 'HTML', 'ubb' => 'BBCode');

		$this->DefaultPrefs = array(
			'code' => 'ubb',
		);

		$this->Code = $this->GetPref('code');

		if (isset($_GET['ajax'])) $this->Ajax = true;
		if ( isset($_SESSION['user']) ) {
			Site::$UserId = $_SESSION['user'];
			Site::$User = new User(Site::$UserId);
			$this->User = Site::$User;
		}

		$this->Url = $_SERVER['REQUEST_URI']; //$this->M->Get('site_url', NULL, TRUE);
		$this->LoginUrl = Site::GetUrl('login', 'back_url=' . urlencode($this->Url));
		$this->RegisterUrl = Site::GetUrl('/register?back_url=') . urlencode($this->Url);

		$this->SetCodeHtmlUrl = Site::GetUrl('set_code', 'code=html&back_url=' . urlencode($this->Url));
		$this->SetCodeBbUrl = Site::GetUrl('set_code', 'code=ubb&back_url=' . urlencode($this->Url));

/*-- GCMS --*/
		$cookie_username = @$_SESSION['gcmsusername'];
		$cookie_password = @$_SESSION['gcmspassword'];

		if ( $cookie_username && $cookie_password /*$cookie_username != null && $cookie_password != null && Global.ValidUser(cookie_username.Value, cookie_password.Value, true)*/ ) {
			$this->GcmsLink = '/lade';
			if ( @$_GET['EditMode'] ) {
				$this->EditMode = site::$EditMode = true;
				//(Page as BasePage).EditMode = true;

				$this->GcmsEditModeOffLink = str_replace('EditMode=1', '', str_replace('&EditMode=1', '', str_replace('?EditMode=1', '', $_SERVER['REQUEST_URI'])));
				$this->GcmsLogoutLink = '/lade/logout?backlink=' . str_replace('EditMode=1', '', str_replace('&EditMode=1', '', str_replace('?EditMode=1', '', $_SERVER['REQUEST_URI'])));
			} else {
				$this->CmsAccess = true;
				$this->GcmsEditModeLink = $_SERVER['REQUEST_URI'];

				if ( strstr($this->GcmsEditModeLink, '?') > -1 ) {
					if ( $_SERVER['QUERY_STRING'] != '') $this->GcmsEditModeLink .= '&';
					$this ->GcmsEditModeLink .= 'EditMode=1';
				} else {
					$this->GcmsEditModeLink .= '?EditMode=1';
				}
				$this->GcmsLogoutLink = '/lade/logout?backlink=' . str_replace('?EditMode=1', '', str_replace('&EditMode=1', '', str_replace('EditMode=1', '', $_SERVER['REQUEST_URI'])));
			}
		} elseif ( @$_GET['EditMode'] ) {
			header('Location: /lade/login?backlink=' . urlencode($_SERVER['REQUEST_URI']));
		}

		//(Page as BasePage).EditMode = EditMode;

		$db_info = $this->Lade();

		$this->Wordlets = new LadeWordlet(Site::$EditMode, $_SERVER['REQUEST_URI'], $db_info->Tables['msnu_wordlet']->Columns['name']->SimpleName, 'msnu_section', 'msnu_wordlet');
		$this->Wordlets->SetConn($db_info->GetConn());
		$this->Wordlets->AddWordlets('site');
/*-- /GCMS --*/
	}

	private $_favorites;
	public function Favorites() {
		if ( !Site::$User ) return NULL;
		if ( $this->_favorites ) return $this->_favorites;

		$this->_favorites = Site::$User->Favorites();

		return $this->_favorites;
	}

	public function GetCleanTag($tag) { 
		@list($tag, $junk) = split(',', $tag);
		return trim($tag);
	}

	public function AddJsFile($file) {
		$this->JsFiles[$file] = $file;
	}

	public function RenderJsFiles($js_files) {
		if ( !is_array($js_files) ) $js_files = array($js_files);

		if ( !$this->M->Get('minify_js') ) {
			/*for ( $i=0; $i < count($js_files); $i++ ) {
				$file = $js_files[$i];
				$js_files[$i] = '/js/' . $file;
			}*/
			echo '/js/' . implode("', '/js/", $js_files);
			return;
		}

		$output = '';
		$lastmod = 0;
		$files = array();

		foreach ( $js_files as $file ) {
			$path = $this->M->Get('js_directory') . $file;
			if ( ($mtime = filemtime($path)) ) {
				if ( $lastmod < $mtime ) $lastmod = $mtime;
				$files[] = $file;
			}
		}

		if ( count($files) ) {
			$filename = $this->M->Get('js_compressed_directory') . implode(',', $files);

			if ( intval(@filemtime($filename)) < $lastmod ) {
				foreach ( $files as $file ) {
					$path = $this->M->Get('js_directory') . $file;
					$output .= "\n" . file_get_contents($path);
				}

				$fp = fopen($filename, 'w+');
				$output = $this->GetCompressedJs($output);
				fwrite($fp, $output);
				fclose($fp);
				chmod($filename, 0777);
			}
			echo '/js/' . $lastmod . '/' . implode(',', $files);
		}
	}

	public function GetCompressedJs($output) {
		$jsp = $this->M->GetObject('JavaScriptPacker', $output, 0);
		$output = $jsp->pack();
		return $output;
	}

	public function IncludeJsFile($file) {
		?><script type="text/javascript"><?
		$path = $this->M->Get('js_directory') . $file;
		$output = file_get_contents($path);
		echo $this->GetCompressedJs($output);
		?></script><?
	}

	public function RenderCssFiles($css_files) {
		if ( !is_array($css_files) ) $css_files = array($css_files);

		if ( !$this->M->Get('minify_css') ) {
			foreach ( $css_files as $file ) {
				echo '<link rel="stylesheet" type="text/css" href="/css/' . $file . '" />';
			}
			return;
		}

		$output = '';
		$lastmod = 0;
		$files = array();

		foreach ( $css_files as $file ) {
			$path = $this->M->Get('css_directory') . $file;
			if ( ($mtime = filemtime($path)) ) {
				if ( $lastmod < $mtime ) $lastmod = $mtime;
				$files[] = $file;
			}
		}

		if ( count($files) ) {
			$filename = $this->M->Get('css_compressed_directory') . implode(',', $files);

			if ( intval(@filemtime($filename)) < $lastmod ) {
				foreach ( $files as $file ) {
					$path = $this->M->Get('css_directory') . $file;
					$output .= "\n" . file_get_contents($path);
				}

				$fp = fopen($filename, 'w+');
				$this->M->IncludeClass('Minify_CSS_Compressor');
				fwrite($fp, Minify_CSS_Compressor::process($output));
				fclose($fp);
				chmod($filename, 0777);
			}
			echo '<link rel="stylesheet" type="text/css" href="/css/' . $lastmod . '/' . implode(',', $files) . '" />';
		}
	}

	public $DbConn = NULL;
	public function GetResult($query) {
		if ( !$this->DbConn ) {
			$this->DbConn = mysql_connect($this->M->Get('DB_ADDR'), $this->M->Get('DB_USER'), $this->M->Get('DB_PASS'));
			mysql_select_db($this->M->Get('DB_NAME'));
		}

		$result = mysql_query($query);
		return $result;
	}

	public function GetPref($pref) {
		if ( !isset($_COOKIE['c' . $pref]) ) {
			if ( isset($this->DefaultPrefs[$pref]) ) {
				return $this->DefaultPrefs[$pref];
			}
			return NULL;
		}
		if ( isset($this->Options[$pref][$_COOKIE['c' . $pref]]) ) return $_COOKIE['c' . $pref];
		return NULL;
	}

	public function SetPref($prefs) {
		foreach ($prefs as $pref => $pref_val) {
			if ( $pref_val ) {
				if ( $pref_val == $this->DefaultPrefs[$pref] ) {
					/*setcookie ('c' . $pref);
					setcookie ('c' . $pref, '');
					setcookie ('c' . $pref, '', time() - 365*24*60*60);
					setcookie ('c' . $pref, '', time() - 365*24*60*60, '/');
					setcookie ('c' . $pref, '', time() - 365*24*60*60, '/', $this->M->Get('cookie_domain'));*/
					setcookie ('c' . $pref, false, time() - 365*24*60*60, '/', $this->M->Get('cookie_domain'), FALSE);
				} else {
					setcookie ('c' . $pref, $pref_val, time() + 365*24*60*60, '/', $this->M->Get('cookie_domain'), FALSE);
				}
				$this->Prefs['c' . $pref] = $pref_val;
			} else {
				$this->Prefs['c' . $pref] = ((isset($_COOKIE['c' . $pref]))?$_COOKIE['c' . $pref]:$this->DefaultPrefs[$pref]);
			}
		}
	}

	private $_tags;
	public function Tags() {
		if ( $this->_tags ) return $this->_tags;
		/*$l = $this->Lade()->_conn;
		$query = "SELECT COUNT(*) AS count, g.dname AS name, g.dimage FROM msnu_smileysgenre AS sg LEFT OUTER JOIN msnu_sgenre AS g ON sg.sgenre_id=g.id GROUP BY g.id ORDER BY count DESC LIMIT 32";
		$result = $l->GetResult($query);
		$this->_tags = array();
		while ( $row = mysql_fetch_assoc($result) ) {
			$row['href'] = '/smileys/' . urlencode($row['name']);
			if ( $row['dimage'] ) {
				$path = $this->M->Get('images_directory') . $row['dimage'];
				if ( file_exists($path) ) {
					list($row['img_width'], $row['img_height'], $attr) = getimagesize($path);
					$row['img_src'] = $this->GetMediaUrl('images/' . $row['dimage']);
				}
			}
			$row['name'] = htmlspecialchars($row['name']);
			$this->_tags[] = $row;
		}*/
		$tag_list = new TagList();
		$tag_list->SetValuesForTopTags(0, 32);
		$this->_tags = $tag_list->Values;
		return $this->_tags;
	}

	/* public function SetUpcomingEvents() {
		if ( $this->this->EditMode ) {
			$events = $this->Lade()->GetList('event', 'ladedgm_event.scheduled>=NOW()', 'ladedgm_event.scheduled', 'ASC');
		} else {
			$events = $this->Lade()->GetList('event', 'ladedgm_event.scheduled>=NOW() && ladedgm_event.enabled=1', 'ladedgm_event.scheduled', 'ASC');
		}
		$this->this->UpcomingEvents = $events->Values;
		$this->this->UpcomingEventsAddLink = $events->AddLink;
	} */

/*-- GCMS -- */
	private $_lade;
	public function Lade() {
		if ( $this->_lade ) return $this->_lade;

		$this->_lade = $this->M->GetObject('Lade', $this->M->Get('DB_ADDR'), $this->M->Get('DB_USER'), $this->M->Get('DB_PASS'), $this->M->Get('DB_NAME'));

		$this->_lade->AddTables($this->M->Get('msnu_tables'));
		$this->_lade->AddSections($this->M->Get('msnu_sections'));

		return $this->_lade;
	}

	/* Template members/methods */
	public $WrapperFile;
	public $ViewFile;
	public function SetWrapperFile($name) {
		$this->WrapperFile = Site::GetViewFile($name);
	}

	public function SetViewFile($name) {
		$this->ViewFile = Site::GetViewFile($name);
	}

	public function RenderViewContent($name) {
		$this->SetViewFile($name);
		$template = $this->M->GetObject('Template');
		if ( !$template->SetFileName($this->ViewFile) ) Monkake::Error('Could not render template:' . $this->ViewFile, TRUE);
		$template->SetPageContent(array('page' => $this));
		if ( $this->WrapperFile ) $template->SetWrapperFileName($this->WrapperFile);
		$template->RenderOutput(array('page' => $this));
	}

	/* public $ForceCacheUpdate = FALSE;
	public $Cache;
	public function EchoCache($cache_name) {
		// set up cache
		$this->Cache = $this->M->GetObject('Cache', $cache_name, Monkavi::Get('cache_path', TRUE));

		$check_paths = array(
			$this->M->Get('controller_path', NULL, TRUE) . Monkavi::Get('controller', TRUE) . '.controller.php',
			$this->M->Get('template_path', NULL, TRUE) . $this->TemplateName . '.tpl.php',
			$this->M->Get('template_path', NULL, TRUE) . $this->TemplateWrapper . '.tpl.php',
		);

		foreach ( $check_paths as $check_path ) {
			if ( filemtime($check_path) > $this->Cache->ModTime ) {
				$this->ForceCacheUpdate = TRUE;
				$this->Cache->SetServeCache(FALSE);
				return;
			}
		}

		return $this->Cache->EchoCache();
	}*/
	public static function GetUrl($url, $query = '') {
		return Site::GetUrl($url, $query);
	}

	public static function GetMediaUrl($path) {
		return Site::GetMediaUrl($path);
	}
}

class Site {
	public static $User; // Logged in user
	public static $UserId; // Logged in user
	public static $EditMode;

	public static function GetMediaUrl($path) {
		$letters = str_split($path);
		$total = 0;
		$servers = Monkake::Get('image_servers');
		foreach ( $letters as $letter ) {
			$total += ord($letter);
		}
		$entry = $total % count($servers);

		return 'http://' . $servers[$entry] . '/' . trim($path);
	}

	public static function GetSmileyUrl($path) {
		$letters = str_split($path);
		$total = 0;
		$servers = Monkake::Get('smiley_servers');
		foreach ( $letters as $letter ) {
			$total += ord($letter);
		}
		$entry = $total % count($servers);

		return 'http://' . $servers[$entry] . '/' . trim($path);
	}

	public static function AddSmileyToFavoritesUrl($id) {
		return Site::GetUrl('set_favorite', 'action=add_favorite&id=' . $id);
	}

	public static function RemoveSmileyFromFavoritesUrl($id) {
		return Site::GetUrl('set_favorite', 'action=remove_favorite&id=' . $id);
	}

	public static function CreateSmileyPostUrl($id) {
		return Site::GetUrl('post', 'type=smiley&id=' . $id . '&back_url=' . urlencode($_SERVER['REQUEST_URI']));
	}

	public static function CreatePostReplyUrl($id) {
		return Site::GetUrl('post', 'type=post&id=' . $id . '&back_url=' . urlencode($_SERVER['REQUEST_URI']));
	}

	public static function GetUrl($url, $query = '') {
		$q = '';
		if ( Site::$EditMode ) $q = '?EditMode=1';
		if ( $q && $query ) {
			$q .= '&' . $query;
		} elseif ($query) {
			$q = '?' . $query;
		}
		return Monkake::Get('site_url') . $url . $q;
	}

	public static function RenderView($file_name, $variables) {
		$template = new Template();
		$file_name = self::GetViewFile($file_name);
		if ( !$template->SetFileName($file_name) ) Monkake::Error('Could not render template:' . $file_name);
		$template->RenderOutput($variables);
	}

	public static function GetViewFile($name) {
		$this_file = Monkake::Get('view_directory', NULL, TRUE) . $name . Monkake::Get('view_append');
		if ( !file_exists($this_file) ) Monkake::Error('Could not render template:' . $this_file, TRUE);
		return $this_file;
	}
}